package com.apache.rpc.tomcat;

import com.apache.passport.common.PassportHelper;
import com.apache.rpc.common.RpcUtil;
import com.apache.tools.StrUtil;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * description: RPC服务统一过滤器
 *
 * @author dyh 创建时间：2018年01月29日
 */
public class RpcServerFilter implements Filter {

    private Logger log = Logger.getLogger(RpcServerFilter.class);

    private static final String SUFFIX = "js,css,png,jpg,gif,bmp,swf,fla,ico";

    private String consoleUser;

    private Map<String, String> unLockMap = new HashMap<String, String>();

    private String writeUrl = "";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //初始化uct服务端 白名单配置
        unLockMap.put("/login.jsp", "");
        unLockMap.put("/main/login", "");
        unLockMap.put("/rpc/service/doService.action", "");
        unLockMap.put("/rpc/service/doService", "");
        StringBuilder sb = new StringBuilder("/health,");//admin 监控白名单
        sb.append("/info,").append("/auditevents,");
        sb.append("/metrics,").append("/logfile,");
        sb.append("/loggers,").append("/jolokia,");
        sb.append("/flyway,").append("/liquibase,");
        sb.append("/dump,").append("/heapdump,");
        sb.append("/auditevents,").append("/env,").append("/turbine,");
        sb.append("/trace,").append("/hystrix,").append("/api,").append("/refresh");
        writeUrl = sb.toString();
        this.consoleUser = RpcUtil.getInstance().getValueByKey("console.user");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
            FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        resp.setCharacterEncoding("UTF-8");

        //获取uri信息
        String uri = req.getRequestURI();
        //获取访问路径
        String servletPath = req.getServletPath();
        //获取后缀名
        String suffix = PassportHelper.getInstance().parseUrlSuffix(uri);
        //后缀名小写
        suffix = suffix.toLowerCase();
        req.getSession().setAttribute("ctx", req.getContextPath());
        //如果存在后缀为图片,css等格式,直接跳过,不拦截
        if (StrUtil.isNotNull(suffix)) {
            if (SUFFIX.contains(suffix)) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }
        if (unLockMap.containsKey(servletPath)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String[] wus = writeUrl.split(",");
        for (int i = 0; i < wus.length; i++) {
            String wurl = wus[i];
            if (servletPath.startsWith(wurl)) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }
        String userName = String.valueOf(req.getSession().getAttribute("userName"));
        //如果不存在.则跳转其他页面,默认为登录页面
//        System.out.println("sessionId=" + req.getSession().getId());
        log.info("uri=" + uri + ";servletPath=" + servletPath + ";login user:" + userName);
        if (StrUtil.isNull(userName) || !consoleUser.equals(userName)) {
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }

    }

    @Override
    public void destroy() {

    }
}
